import { UserOutlined } from "@ant-design/icons"
import { Tree } from "antd"
import React, { FC, useEffect, useState } from "react"

import { DataNode } from "@/components/common/tree/types"
import { useApi } from "@/hooks"

const DxTree: FC<{
	onSelect: (key: string, userId: string) => void
	searchKey?: string
	nameType?: number
	needExpand?: boolean
	needMember?: boolean
}> = props => {
	const { generalHttp } = useApi()
	const [rootData, setRoot] = useState<DataNode[]>([])
	const getRootData = async (params?: { id: string; merchantId: string }) => {
		const [error, ret] = await generalHttp<any>("/proxyList/generalProxyList", params)
		if (error) return
		const retData: DataNode[] = ret.map((item: { id: string; userName: string; underProxyNum: number; merchantId: string }) => {
			return {
				key: item.id + "--" + item.merchantId,
				title: `${item.userName}\t${item.underProxyNum}/${item.underProxyNum}`
			}
		})
		setRoot(retData)
	}
	type linkType = {
		id: string
		merchantId: string
		userName: string
		underProxyNum: number
		childList: linkType[]
	}
	const handleLink = (linkDatas: linkType[], tempExpand: string[] = []): DataNode[] => {
		const data = linkDatas.map(item => {
			if (!item.childList || item.childList.length === 0) {
				selectNode([item.id + "--" + item.merchantId], {
					node: { title: `${item.userName}\t${item.underProxyNum}/${item.underProxyNum}` }
				})
				setExpand(tempExpand)
				return {
					key: item.id + "--" + item.merchantId,
					title: `${item.userName}\t${item.underProxyNum}/${item.underProxyNum}`
				}
			} else {
				tempExpand.push(item.id + "--" + item.merchantId)
				return {
					key: item.id + "--" + item.merchantId,
					title: `${item.userName}\t${item.underProxyNum}/${item.underProxyNum}`,
					children: handleLink(item.childList, tempExpand)
				}
			}
		})
		return data
	}
	const getArr = (list: DataNode[], arr: string[]) => {
		if (list[0]) {
			arr.push(list[0].key)
			if (list[0].children) getArr(list[0].children, arr)
		}
	}
	const [keyArr, setKeyArr] = useState<string[]>([])
	const search = async (key: string) => {
		const dataArr: string[] = []
		const [error, ret] = await generalHttp("/proxyList/levelLinkByUserName", { name: key, nameType: 1 })
		if (!error) {
			let filterData = handleLink(ret as linkType[])
			setRoot(filterData)
			getArr(filterData, dataArr)
			setKeyArr(dataArr)
		} else setRoot([])
	}
	useEffect(() => {
		if (keyArr.length === 0) return
		const key = keyArr.shift()
		loadData({ key })
	}, [rootData])
	// useEffect(() => {
	// 	getRootData()
	// }, [])
	useEffect(() => {
		if (!props.searchKey) {
			setSelect([])
			getRootData()
		} else {
			search(props.searchKey)
		}
	}, [props.searchKey])
	type RetType = { id: string; userName: string; underProxyNum: number; merchantId: string; childList: RetType[] }
	const handleRet = (data: RetType): DataNode => {
		return {
			key: data.id + "--" + data.merchantId,
			title: `${data.userName}\t${data.underProxyNum}/${data.underProxyNum}`,
			children: data.childList?.map(item => handleRet(item)) ?? []
		}
	}
	const findItem = (list: DataNode[], key: string, target: DataNode): boolean => {
		return list.some(item => {
			if (item.key === key) {
				item.children = target.children
				return true
			} else if (!item.children) {
				return false
			}
			return findItem(item.children, key, target)
		})
	}
	const updateTree = async (list: DataNode[], key: string) => {
		const [id, merchantId] = key.split("--")
		const [error, ret] = await generalHttp("/proxyList/levelLink", { id, merchantId })
		if (error) return
		const retData = handleRet(ret as RetType)
		if (props.needMember) {
			const [error1, ret1] = await generalHttp("/report/proxyTree/getMemberMainInfo", { parentProxyId: id, merchantId })
			if (!error1) {
				;(ret1 as any[]).forEach(item => {
					if (!retData.children) retData.children = []
					retData.children.unshift({
						key: item.id + "--" + item.merchantId + "--leaf",
						title: `${item.userName}`,
						icon: <UserOutlined />,
						isLeaf: true
					})
					// setExpand([...expandedKeys, item.id + "--" + item.merchantId + "--leaf"])
				})
			}
		}
		const listCopy = JSON.parse(JSON.stringify(list))
		findItem(listCopy, key, retData)
		setRoot(listCopy)
		// setTimeout(() => {
		setExpand([...expandedKeys, key])
		return listCopy
		// }, 2000)
	}
	const selectNode = (keys: any, e: any) => {
		const key = keys[0]
		if (selectedKeys.includes(key)) return
		setSelect([key])
		props.onSelect(e.node.title.split(`\t`)[0], key.split("--")[0])
	}
	const loadData = async ({ key }: any) => {
		if (key.includes("--leaf")) return
		if (selectedKeys.includes(key) && !props.needExpand) return
		await updateTree(rootData, key)
	}
	const [selectedKeys, setSelect] = useState<string[]>([])
	const [expandedKeys, setExpand] = useState<string[]>([])
	return (
		<div id="tree" className="hfull ova">
			{rootData.length > 0 ? (
				<Tree
					treeData={rootData}
					onSelect={selectNode}
					loadData={loadData}
					selectedKeys={selectedKeys}
					expandedKeys={expandedKeys}
					// showIcon
				/>
			) : (
				<div>暂无数据</div>
			)}
		</div>
	)
}

export default DxTree
